import { reactive, ref } from 'vue'
import type { PaginationState, TableOptions, TableState } from '../types'

export function useTable(options: TableOptions) {
  // 表格状态
  const state = reactive<TableState>({
    data: options.data || [],
    loading: options.loading || false,
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layout: 'total, sizes, prev, pager, next, jumper',
      ...options.pagination,
    },
  })

  // 表格引用
  const tableRef = ref()

  // 方法
  const methods = {
    // 设置数据
    setData: (data: any[]) => {
      state.data = data
    },

    // 设置加载状态
    setLoading: (loading: boolean) => {
      state.loading = loading
    },

    // 设置分页信息
    setPagination: (pagination: Partial<PaginationState>) => {
      Object.assign(state.pagination, pagination)
    },

    // 刷新表格
    reload: () => {
      return {
        page: state.pagination.currentPage,
        pageSize: state.pagination.pageSize,
        timestamp: Date.now(),
      }
    },

    // 清除选择
    clearSelection: () => {
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    },

    // 切换行选择状态
    toggleRowSelection: (row: any, selected?: boolean) => {
      if (tableRef.value) {
        tableRef.value.toggleRowSelection(row, selected)
      }
    },

    // 切换全选状态
    toggleAllSelection: () => {
      if (tableRef.value) {
        tableRef.value.toggleAllSelection()
      }
    },
  }

  return {
    state,
    tableRef,
    ...methods,
  }
}
